from fastapi import FastAPI, HTTPException
from fastapi.responses import PlainTextResponse
from pdf2image import convert_from_path
from pathlib import Path
from dotenv import load_dotenv
import os
import shutil
import requests
import pdfplumber
import pytesseract
import uuid

load_dotenv()

app = FastAPI(title="建设用地接口")

# 临时目录用于存储上传和输出文件
TEMP_DIR = Path("temp")
OUTPUT_DIR = Path("output")
# DeepSeek configuration
model_name=os.getenv("DEEPSEEK_MODEL")
api_key=os.getenv("DEEPSEEK_API_KEY")
base_url=os.getenv("DEEPSEEK_API_URL")
base_ydsp_url=os.getenv("BASE_YDSP_URL")
# Summarization prompt
SUMMARIZATION_PROMPT =""
@app.on_event("startup")
async def startup_event():
    # 创建临时和输出目录
    TEMP_DIR.mkdir(exist_ok=True)
    OUTPUT_DIR.mkdir(exist_ok=True)

def is_text_pdf(pdf_path, min_text_length=50):
    """检测 PDF 是否为文本型，返回 True 表示文本型，False 表示扫描版/图片型"""
    try:
        with pdfplumber.open(pdf_path) as pdf:
            text = ''
            for page in pdf.pages:
                extracted_text = page.extract_text()
                if extracted_text:
                    text += extracted_text
            # 如果提取的文本长度足够长，认为是文本型 PDF
            return len(text.strip()) > min_text_length
    except Exception:
        return False

def extract_text_pdf(pdf_path):
    """处理文本型 PDF，使用 pdfplumber 提取文本"""
    try:
        with pdfplumber.open(pdf_path) as pdf:
            text = ''
            for page in pdf.pages:
                extracted_text = page.extract_text()
                if extracted_text:
                    text += extracted_text + '\n'
            return text.strip()
    except Exception as e:
        return f"Error extracting text PDF: {str(e)}"
def extract_text_pdf(pdf_path):
    """处理文本型 PDF，使用 pdfplumber 提取文本"""
    try:
        with pdfplumber.open(pdf_path) as pdf:
            text = ''
            for page in pdf.pages:
                extracted_text = page.extract_text()
                if extracted_text:
                    text += extracted_text + '\n'
            return text.strip()
    except Exception as e:
        return f"Error extracting text PDF: {str(e)}"

def extract_image_pdf(pdf_path, lang='chi_sim'):
    """处理扫描版/图片型 PDF，转换为图片并用 pytesseract 进行 OCR"""
    try:
        # 将 PDF 转换为图片
        images = convert_from_path(pdf_path)
        text = ''
        for image in images:
            # OCR 提取文本，支持中文
            extracted_text = pytesseract.image_to_string(image, lang=lang)
            text += extracted_text + '\n'
        return text.strip()
    except Exception as e:
        return f"Error extracting image PDF: {str(e)}"

def extract_pdf_text(pdf_path, lang='chi_sim', min_text_length=50):
    """主函数：自动检测 PDF 类型并提取文本"""
    if not os.path.exists(pdf_path):
        return "Error: PDF file does not exist."
    
    # 检测 PDF 类型
    if is_text_pdf(pdf_path, min_text_length):
        # 文本型 PDF
        return extract_text_pdf(pdf_path)
    else:
        # 扫描版/图片型 PDF
        return extract_image_pdf(pdf_path, lang)
# 从 REST API 获取 JSON 数据
def fetch_json_from_api(url,params):
    try:
        response = requests.get(url,params)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()  # 解析 JSON 数据
    except requests.exceptions.RequestException as e:
        print(f"Error fetching JSON from API: {e}")
        return []
def fetch_text_from_api(url,params):
    try:
        response = requests.get(url,params)
        response.raise_for_status()  # 检查请求是否成功
        return response.text  # 解析 JSON 数据
    except requests.exceptions.RequestException as e:
        print(f"Error fetching JSON from API: {e}")
        return []
def sumText(prompt):
    
    print(f"prompt text: {prompt}")
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    payload = {
         "model": model_name,
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "max_tokens": 2000,
        "stream": False
    }
    response = requests.post(base_url, headers=headers, json=payload)
    if response.status_code != 200:
        raise HTTPException(status_code=500, detail=f"DeepSeek API failed: {response.text}") 
    summary = response.json()["choices"][0]["message"]["content"]
    return summary

@app.get("/readPdfData", response_class=PlainTextResponse)
async def read_pdf_url(pdf_url):

    try:
        if not pdf_url.lower().endswith(".pdf"):
            raise HTTPException(status_code=400, detail="URL must point to a PDF file")

        # Download PDF
        response = requests.get(pdf_url, stream=True)
        if response.status_code != 200:
            raise HTTPException(status_code=400, detail=f"Failed to download PDF: {response.status_code}")

        # Extract filename from URL
        original_name =  original_name = str(uuid.uuid4()).replace('-', '')
        temp_pdf_path = TEMP_DIR / f"{original_name}.pdf"

        # Save PDF
        with open(temp_pdf_path, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        print(f"Temporary PDF path: {temp_pdf_path}")

        result = extract_pdf_text(temp_pdf_path, lang='chi_sim')  # 中文 PDF 使用 chi_sim
   
        prompt = f"转换以下文本为Markdown格式:\n\n{result}\n\n不需要进行总结，原文本内容不要丢失，只把文本中的页码标记部分删掉:"
        print(f"prompt text: {prompt}")
        summary = sumText(prompt)

        #Clean up
        os.unlink(temp_pdf_path)

        return summary

    except Exception as e:
        # 清理临时文件（如果存在）
        if "temp_pdf_path" in locals():
            try:
                os.unlink(temp_pdf_path)
            except:
                pass
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/fetch_xm_files", response_class=PlainTextResponse)
async def fetch_xm_files(xmbh:int):
    params = {
        "bucket": "upload-ydk",
        "classify": "10-1",
        "fid":xmbh
    }
    fatch_api_url = f"{base_ydsp_url}/uploader/getTreeByFid"
    data = fetch_json_from_api(fatch_api_url,params)
    print(f"fetch_json_from_api: {data}")
    try:
        target_data = data.get("data")[0].get("children").get("children")
        prompt = f"转换以下JSON为Markdown格式:\n\n{target_data}\n\n只保留title、url属性，Markdown附件文件设置文件名的超链接，链接拼接格式是：{base_ydsp_url}+url"
        result = sumText(prompt)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error processing JSON data: {data}")
@app.on_event("shutdown")
async def shutdown_event():
    # 清理临时目录
    shutil.rmtree(TEMP_DIR, ignore_errors=True)
    shutil.rmtree(OUTPUT_DIR, ignore_errors=True)